<?php

/*
 * Fresns Control Panel (Standalone)
 * Copyright (C) 2021-Present 刘鑫
 * Released under the MIT License.
 */

namespace App\Plugins\FcpApi\TweetConfigs;

use App\Http\Center\Common\ErrorCodeService;
use App\Http\Center\Common\ValidateService;
use App\Http\FresnsApi\Helpers\ApiConfigHelper;
use App\Http\FresnsApi\Helpers\ApiFileHelper;
use App\Http\FresnsApi\Helpers\ApiLanguageHelper;
use App\Plugins\FcpApi\Base\TweetBaseController;
use App\Plugins\FcpApi\TweetFiles\TweetFiles;
use App\Plugins\FcpApi\TweetLanguages\TweetLanguages;
use App\Plugins\FcpApi\TweetPluginUsages\TweetPluginUsages;
use App\Plugins\FcpApi\TweetPluginUsages\TweetPluginUsagesService;
use Illuminate\Http\Request;

class FsControllerAdmin extends TweetBaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->service = new FsService();
    }

    public function index(Request $request)
    {
        $tag = $request->input('tag');
        $languageArr = TweetConfigService::getLanguageStatus();
        $languagesOption = $languageArr['languagesOption'];
        //是否开启多语言
        $languageStatus = ApiConfigHelper::getConfigByItemKey('language_status');
        //默认语言
        $defaultLanguage = ApiConfigHelper::getConfigByItemKey(FsConfig::DEFAULT_LANGUAGE);


        if ($tag == FsConfig::LANGUAGE_TAG) {
            $request->offsetSet('item_key',FsConfig::LANGUAGE_MENUS);
            parent::index($request);
        } else {
            $tagArr = explode(',', $tag);
            $itemArr = FsModel::whereIn('item_tag', $tagArr)->get(['item_key', 'item_value', 'item_tag', 'item_type'])->toArray();
            $arr = [];
            foreach ($itemArr as $v) {
                $item = [];
                $item['alias_key'] = $v['item_key'];
                $item['item_type'] = $v['item_type'];
                $item['item_value'] = $v['item_value'];
                $item['item_file'] = null;
                if ($v['item_type'] == 'checkbox' || $v['item_type'] == 'select') {
                    if (strstr($item['item_value'], ',')) {
                        $item['item_value'] = explode(',', $v['item_value']);
                    }
                }
                if ($v['item_type'] != 'file') {
                    if ($v['item_value'] == 'true') {
                        $item['item_value'] = true;
                    }
                    if ($v['item_value'] == 'false') {
                        $item['item_value'] = false;
                    }
                } else {
                    $item['item_file'] = ApiFileHelper::getImageSignUrl($v['item_value']);
                }

                if ($item['alias_key'] == 'send_sms_code_more') {
                    $value = json_decode($item['item_value'], true);
                    $item['item_value'] = implode('n', $value);
                }
                //查询对应的语言
                $langMap = TweetLanguages::where('table_name', TweetConfigsConfig::CFG_TABLE)->where('table_key', $v['item_key'])->pluck('lang_content', 'lang_tag')->toArray();
                $languageArr = [];
                if ($langMap) {
                    if($languageStatus === false){
                        foreach ($languagesOption as $languages) {
                            if($languages['key'] == $defaultLanguage){
                                $it = [];
                                $it['key'] = $languages['key'];
                                $it['text'] = $languages['text'];
                                $it['lang_content'] = $langMap[$languages['key']] ?? '';
                                $languageArr[] = $it;
                            }
                        }
                    } else {
                        foreach ($languagesOption as $languages) {
                            $it = [];
                            $it['key'] = $languages['key'];
                            $it['text'] = $languages['text'];
                            $it['lang_content'] = $langMap[$languages['key']] ?? '';
                            $languageArr[] = $it;
                        }
                    }
                    
                }

                $item['lang_json_arr'] = $languageArr;
                $arr[] = $item;
            }
            $list = [];
            if (! empty($arr)) {
                $list['id'] = 1;
                $list['key'] = 1;

                $list['item_key'] = $tag;
                $list['item_value_decode'] = $arr;
                $list = [$list];
            }

            $data['list'] = $list;
            // common 数据
            $data['common'] = $this->service->common();

            //分页
            $data['pagination']['total'] = empty($arr) ? 0 : 1;
            $data['pagination']['current'] = 1;
            $data['pagination']['pageSize'] = 30;

            $this->success($data);
        }
    }

    public function update(Request $request)
    {
        // 校验参数
        $rule = [
            'config_json' => 'required|json',
        ];
        // ValidateService::validateRule($request, $rule);
        $json = $request->input('config_json');
        $json = stripslashes($json);
        $configArr = json_decode($json, true);
        if (empty($configArr)) {
            $this->error(ErrorCodeService::CODE_PARAM_ERROR);
        }
        $this->service->updateConfigs($configArr);

        $this->success();
    }

    //新增语言设置
    public function storeLang(Request $request)
    {
        $rankNum = $request->input('rankNum', null);
        $langCode = $request->input('langCode', null);
        $langName = $request->input('langName', null);
        $writingDirection = $request->input('writingDirection', null);
        $areaCode = $request->input('areaCode', null);
        $areaName = $request->input('areaName', null);
        $dateFormat = $request->input('dateFormat', null);
        $timeFormatMinute = $request->input('timeFormatMinute', null);
        $timeFormatHour = $request->input('timeFormatHour', null);
        $timeFormatDay = $request->input('timeFormatDay', null);
        $timeFormatMonth = $request->input('timeFormatMonth', null);
        $lengthUnits = $request->input('lengthUnits', null);
        $continentId = $request->input('continentId', null);
        $isEnable = $request->input('isEnable', null);
        $packVersion = $request->input('packVersion', null);
        $areaStatus = $request->input('areaStatus', null);

        $data = [
            'rankNum' => $rankNum,
            'langCode' => $langCode,
            'langName' => $langName,
            'continentId' => $continentId,
            'areaCode' => $areaCode,
            'areaName' => $areaName,
            'langTag' => $langCode.'-'.$areaCode,
            'writingDirection' => $writingDirection,
            'lengthUnits' => $lengthUnits,
            'dateFormat' => $dateFormat,
            'timeFormatMinute' => $timeFormatMinute,
            'timeFormatHour' => $timeFormatHour,
            'timeFormatDay' => $timeFormatDay,
            'timeFormatMonth' => $timeFormatMonth,
            'packVersion' => $packVersion,
            'isEnable' => $isEnable,
            'areaStatus' => $areaStatus,
        ];
        if (empty($data['areaCode'])) {
            $data['langTag'] = $langCode;
        }
        //查询是否有语言设置
        $langSettings = FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->first();
        if ($langSettings) {
            $oldLangSettingJson = $langSettings['item_value'];
            $oldLangSettingArr = json_decode($oldLangSettingJson, true);
            $isTrue = true;
            if ($oldLangSettingArr) {
                foreach ($oldLangSettingArr as $v) {
                    if ($v['langTag'] == $data['langTag']) {
                        $isTrue = false;
                    }
                }
            }

            if ($isTrue == true) {
                $oldLangSettingArr[] = $data;
                $input = [
                    'item_key' => FsConfig::LANGUAGE_MENUS,
                    'item_tag' => FsConfig::LANGUAGE_TAG,
                    'item_value' => json_encode($oldLangSettingArr),
                ];
                FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->update($input);
            } else {
                $this->error(ErrorCodeService::LANGUAGE_SETTING_ERROR);
            }
        } else {
            $input = [
                'item_key' => FsConfig::LANGUAGE_MENUS,
                'item_tag' => FsConfig::LANGUAGE_TAG,
                'item_value' => json_encode([$data]),
            ];
            FsModel::insert($input);

            $languageStatus = FsModel::where('item_key', FsConfig::DEFAULT_LANGUAGE)->first();
            $data['alias_key'] = FsConfig::DEFAULT_LANGUAGE;
            $data['item_value'] = $data['key'];
            $data['item_type'] = 'string';
            if ($languageStatus) {
                if ($data['langTag']) {
                    $input = [
                        'item_value' => json_encode($data),
                    ];
                    FsModel::where('item_key', FsConfig::DEFAULT_LANGUAGE)->update($input);
                }
            } else {
                $input = [
                    'item_key' => FsConfig::DEFAULT_LANGUAGE,
                    'item_tag' => FsConfig::LANGUAGE_TAG,
                    'item_value' => json_encode($data),
                ];
                FsModel::insert($input);
            }
        }

        $this->success();
    }

    //编辑语言设置
    public function updateLang(Request $request)
    {
        $rankNum = $request->input('rankNum', null);
        $langCode = $request->input('langCode', null);
        $langName = $request->input('langName', null);
        $writingDirection = $request->input('writingDirection', null);
        $areaCode = $request->input('areaCode', null);
        $areaName = $request->input('areaName', null);
        $dateFormat = $request->input('dateFormat', null);
        $timeFormatMinute = $request->input('timeFormatMinute', null);
        $timeFormatHour = $request->input('timeFormatHour', null);
        $timeFormatDay = $request->input('timeFormatDay', null);
        $timeFormatMonth = $request->input('timeFormatMonth', null);
        $lengthUnits = $request->input('lengthUnits', null);
        $continentId = $request->input('continentId', null);
        $packVersion = $request->input('packVersion', null);
        $isEnable = $request->input('isEnable', null);
        $areaStatus = $request->input('areaStatus', null);

        $key = $request->input('langTag', null);
        $data = [
            'rankNum' => $rankNum,
            'langCode' => $langCode,
            'langName' => $langName,
            'continentId' => $continentId,
            'areaCode' => $areaCode,
            'areaName' => $areaName,
            'langTag' => $langCode.'-'.$areaCode,
            'writingDirection' => $writingDirection,
            'lengthUnits' => $lengthUnits,
            'dateFormat' => $dateFormat,
            'timeFormatMinute' => $timeFormatMinute,
            'timeFormatHour' => $timeFormatHour,
            'timeFormatDay' => $timeFormatDay,
            'timeFormatMonth' => $timeFormatMonth,
            'packVersion' => $packVersion,
            'isEnable' => $isEnable,
            'areaStatus' => $areaStatus,
        ];
        if (empty($data['areaCode'])) {
            $data['langTag'] = $langCode;
        }

        //查询是否有语言设置
        $langSettings = FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->first();
        if ($langSettings) {
            $oldLangSettingJson = $langSettings['item_value'];
            $oldLangSettingArr = json_decode($oldLangSettingJson, true);
            $isTrue = false;
            if ($oldLangSettingArr) {
                foreach ($oldLangSettingArr as $v) {
                    if ($v['langTag'] == $key) {
                        $isTrue = true;
                    }
                }
            }

            if ($isTrue == true) {
                $itemArr = [];
                foreach ($oldLangSettingArr as $v) {
                    if ($v['langTag'] == $key) {
                        $v = $data;
                    }
                    $itemArr[] = $v;
                }

                $oldLangSettingArr[] = $data;
                $input = [
                    'item_key' => FsConfig::LANGUAGE_MENUS,
                    'item_tag' => FsConfig::LANGUAGE_TAG,
                    'item_value' => json_encode($itemArr),
                ];
                FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->update($input);
            } else {
                $this->error(ErrorCodeService::LANGUAGE_SETTING_ERROR);
            }
        }

        $this->success();
    }

    //获取地区代码
    public function getAreaCode(Request $request)
    {
        $id = $request->input('id');

        //获取地区代码
        $areasArr = FsService::getItemValueArrByItemKey(FsConfig::AREAS);

        $itemArr = [];
        foreach ($areasArr as $area) {
            if ($area['continentId'] != $id) {
                continue;
            }
            $area['name_desc'] = $area['name'].' - '.$area['localName'].' > '.$area['code'];
            $itemArr[] = $area;
        }
        $data['list'] = $itemArr;
        $this->success($data);
    }

    //排序
    public function updateRankNum(Request $request)
    {
        $json = $request->input('more_json');
        $jsonArr = json_decode($json, true);
        $langSettings = FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->first();
        if ($langSettings) {
            $oldLangSettingJson = $langSettings['item_value'];
            $oldLangSettingArr = json_decode($oldLangSettingJson, true);
            $newArr = [];
            foreach ($oldLangSettingArr as $v) {
                foreach ($jsonArr as $value) {
                    if ($value['langTag'] == $v['langTag']) {
                        $v['rankNum'] = $value['rank_num'];
                    }
                }
                $newArr[] = $v;
            }
            $input = [
                'item_key' => FsConfig::LANGUAGE_MENUS,
                'item_tag' => FsConfig::LANGUAGE_TAG,
                'item_value' => json_encode($newArr),
            ];
            FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->update($input);
        }

        $this->success();
    }

    //删除
    public function destroyLang(Request $request)
    {
        $key = $request->input('ids');
        $keyArr = explode(',', $key);

        //默认
        // $defaultLanguage = FsModel::where('item_key',FsConfig::DEFAULT_LANGUAGE)->value('item_value');
        // $defaultLanguageArr = json_decode($defaultLanguage,true);
        $languageArr = TweetConfigService::getLanguageStatus();

        $defaultLanguage = $languageArr['default_language'];
        if (in_array($defaultLanguage, $keyArr)) {
            $this->errorInfo(ErrorCodeService::DELETE_CONTENT_ERROR, '默认语言不允许删除');
        }

        $langSettings = FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->first();
        $oldLangSettingJson = $langSettings['item_value'];
        $oldLangSettingArr = json_decode($oldLangSettingJson, true);
        $itemArr = [];
        $destroyArr = [];
        foreach ($oldLangSettingArr as $v) {
            if (in_array($v['langTag'], $keyArr)) {
                $lang = $v['langTag'];
                $destroyArr[] = $lang;
                continue;
            }
            $itemArr[] = $v;
        }

        TweetLanguages::whereIn('lang_tag', $destroyArr)->delete();

        $input = [
            'item_key' => FsConfig::LANGUAGE_MENUS,
            'item_tag' => FsConfig::LANGUAGE_TAG,
            'item_value' => json_encode($itemArr),
        ];
        FsModel::where('item_key', FsConfig::LANGUAGE_MENUS)->update($input);

        $this->success();
    }

    //是否开启多语言
    public function updateLanguageStatus(Request $request)
    {
        $language_status = $request->input('language_status');
        $languageStatus = FsModel::where('item_key', FsConfig::LANGUAGE_STATUS)->first();
        $data['alias_key'] = FsConfig::LANGUAGE_STATUS;
        $data['item_value'] = $language_status;
        $data['item_type'] = 'boolean';
        if ($language_status == 'true') {
            $status = 'true';
        } else {
            $status = 'false';
        }
        if ($languageStatus) {
            $input = [
                'item_value' => $status,
            ];
            FsModel::where('item_key', FsConfig::LANGUAGE_STATUS)->update($input);
        } else {
            $input = [
                'item_key' => FsConfig::LANGUAGE_STATUS,
                'item_tag' => FsConfig::LANGUAGE_TAG,
                'item_value' => $status,
            ];
            FsModel::insert($input);
        }

        $this->success();
    }

    //默认语言
    public function updateDefaultLanguage(Request $request)
    {
        $key = $request->input('langTag');
        // $defaultKey =  ApiLanguageHelper::getDefaultLanguageByKey($key);
        $languageStatus = FsModel::where('item_key', FsConfig::DEFAULT_LANGUAGE)->first();
        $data['alias_key'] = FsConfig::DEFAULT_LANGUAGE;
        $data['item_value'] = $key;
        $data['item_type'] = 'string';
        if ($languageStatus) {
            if ($key) {
                $input = [
                    'item_value' => $key,
                ];
                FsModel::where('item_key', FsConfig::DEFAULT_LANGUAGE)->update($input);
            }
        } else {
            $input = [
                'item_key' => FsConfig::DEFAULT_LANGUAGE,
                'item_tag' => FsConfig::LANGUAGE_TAG,
                'item_value' => $key,
            ];
            FsModel::insert($input);
        }

        $this->success();
    }

    //语言包列表
    public function packIndex(Request $request)
    {
        // 校验参数
        $rule = [
            'lang_tag'    => 'required',
        ];
        ValidateService::validateRule($request, $rule);
        $lang_tag = $request->input('lang_tag');
        $langTagJson = FsModel::where('item_key', $lang_tag)->value('item_value');
        $langTagArr = json_decode($langTagJson, true);
        $langTagMap = [];
        if ($langTagArr) {
            foreach ($langTagArr as $v) {
                $langTagMap[$v['name']] = $v['content'];
            }
        }

        $packJson = FsModel::where('item_key', 'language_pack')->value('item_value');
        $packArr = json_decode($packJson, true);

        //查询默认是否有
        $defaultLanguage = ApiLanguageHelper::getDefaultLanguage();

        $defaultLangTagJson = FsModel::where('item_key', $defaultLanguage)->value('item_value');
        $defaultLangTagArr = json_decode($defaultLangTagJson, true);
        $defaultLangTagArrMap = [];
        if ($defaultLangTagArr) {
            foreach ($defaultLangTagArr as $v) {
                $defaultLangTagArrMap[$v['name']] = $v['content'];
            }
        }

        $list = [];
        foreach ($packArr as $v) {
            $item = [];
            $item['key'] = $v['name'];
            $item['name'] = $v['name'];
            $item['canDelete'] = $v['canDelete'];
            $item['default_content'] = $defaultLangTagArrMap[$v['name']] ?? '';
            $item['content'] = $langTagMap[$v['name']] ?? '';
            $list[] = $item;
        }

        $data['list'] = $list;
        // common 数据
        $data['common'] = $this->service->common();

        //分页
        $data['pagination']['total'] = count($list);
        $data['pagination']['current'] = 1;
        $data['pagination']['pageSize'] = 500;

        $this->success($data);
    }

    //语言包新增
    public function packStore(Request $request)
    {
        // 校验参数
        $rule = [
            'lang_tag'    => 'required',
            'pack_json'    => 'required',
        ];
        ValidateService::validateRule($request, $rule);

        $json = $request->input('pack_json');
        $langTag = $request->input('lang_tag');
        $packArr = json_decode($json, true);
        //校验
        $old = count($packArr);
        $newArr = [];
        foreach ($packArr as $v) {
            $newArr[$v['name']] = $v;
        }
        if ($old != count($newArr)) {
            $this->error(ErrorCodeService::SETTING_ERROR);
        }
        $packJson = FsModel::where('item_key', 'language_pack')->value('item_value');
        $packJsonArr = json_decode($packJson, true);
        $this->service->packStore($langTag, $packArr, $packJsonArr);

        $this->success();
    }

    public function packUpdate(Request $request)
    {
        // 校验参数
        $rule = [
            'key'    => 'required',
            'lang_tag'    => 'required',
        ];
        ValidateService::validateRule($request, $rule);

        $key = $request->input('key');
        $lang_tag = $request->input('lang_tag');
        $name = $request->input('name');
        $content = $request->input('content');

        $itemValue = FsModel::where('item_key', $lang_tag)->value('item_value');
        $langTagArr = json_decode($itemValue, true);

        $itemArr = [];
        foreach ($langTagArr as $v) {
            if ($v['name'] == $key) {
                // $v['name'] = $name;
                $v['content'] = $content;
            }
            $itemArr[] = $v;
        }

        FsModel::where('item_key', $lang_tag)->update(['item_value' => json_encode($itemArr)]);

        $this->success();
    }

    public function packDestroy(Request $request)
    {
        // 校验参数
        $rule = [
            'lang_tag'    => 'required',
            'key'    => 'required',
        ];
        ValidateService::validateRule($request, $rule);

        $key = $request->input('key');
        $langTag = $request->input('lang_tag');
        $itemValue = FsModel::where('item_key', $langTag)->value('item_value');
        $langTagArr = json_decode($itemValue, true);
        $itemArr = [];
        $name = null;
        if ($langTagArr) {
            foreach ($langTagArr as $v) {
                if ($v['name'] == $key) {
                    $name = $v['name'];
                    continue;
                }
                $itemArr[] = $v;
            }
        }

        $packJson = FsModel::where('item_key', 'language_pack')->value('item_value');
        $packJsonArr = json_decode($packJson, true);

        $newPackArr = [];
        foreach ($packJsonArr as $v) {
            if ($v['name'] == $name) {
                if ($v['canDelete'] == false) {
                    $this->error(ErrorCodeService::DELETE_ERROR);
                }
                continue;
            }
            $newPackArr[] = $v;
        }

        FsModel::where('item_key', 'language_pack')->update(['item_value' => $newPackArr]);

        FsModel::where('item_key', $langTag)->update(['item_value' => json_encode($itemArr)]);
        $this->success();
    }

    //地图设置-列表
    public function mapIndex(Request $request)
    {
        $service = new TweetPluginUsagesService();
        $request->offsetSet('type', 9);
        $service->setResource(TweetPluginUsagesResource::class);
        $data = $service->searchData();
        $this->success($data);
    }

    //地图设置-新增
    public function mapStore(Request $request)
    {
        $itemKey = $request->input('item_key');
        $item_json = $request->input('item_json');
        $map_id = $request->input('map_id');
        $map_name = $request->input('map_name');
        $map_plugin = $request->input('map_plugin');

        $count = TweetPluginUsages::where('type', 9)->where('parameter', $map_id)->where('plugin_unikey', $map_plugin)->count();
        if ($count > 0) {
            $this->error(ErrorCodeService::SETTING_ERROR);
        }

        $mapCount = FsModel::where('item_key', $itemKey)->count();

        if ($mapCount > 0) {
            FsModel::where('item_key', $itemKey)->update(['item_value' => $item_json]);
        } else {
            $input = [
                'item_key' => $itemKey,
                'item_value' => $item_json,
                'item_tag' => FsConfig::MAP,
                'item_type' => 'array'
            ];

            FsModel::insert($input);
        }

        $pluginInput = [
            'type' => 9,
            'name' => $map_name,
            'plugin_unikey' => $map_plugin,
            'parameter' => $map_id,
        ];
        TweetPluginUsages::insert($pluginInput);
        $this->success();
    }

    //地图设置-编辑
    public function mapUpdate(Request $request)
    {
        $id = $request->input('id');
        $is_enable = $request->input('is_enable');

        TweetPluginUsages::where('id', $id)->update(['is_enable' => $is_enable]);

        $this->success();
    }

    // 验证规则
    public function rules($ruleType)
    {
        $rule = [];

        $config = new FsConfig($this->service->getTable());

        switch ($ruleType) {
            case FsConfig::RULE_STORE:
                $rule = $config->storeRule();
                break;

            case FsConfig::RULE_UPDATE:
                $rule = $config->updateRule();
                break;

            case FsConfig::RULE_DESTROY:
                $rule = $config->destroyRule();
                break;

            case FsConfig::RULE_DETAIL:
                $rule = $config->detailRule();
                break;
        }

        return $rule;
    }
}
